package com.peycard.vista;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.validator.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.peycard.common.ReaderControlDTO;
import com.peycard.service.BaseService;
import com.peycard.util.Constantes;
import com.peycard.util.Utils;

@Controller(Constantes.BEAN_CONTROL)
@Scope(Constantes.SCOPE_SESSION)
public class ControlDispositivosControlador extends BaseController implements
		Serializable {

	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(DispositivosControlador.class);
	@NotEmpty
	private String idReaderControl;
	@NotEmpty
	private String brand;
	@NotEmpty
	private String isActive;
	@NotEmpty
	private String model;
	@NotEmpty
	private String platform;
	@NotEmpty
	private String newBrand;
	@NotEmpty
	private String newIsActive;
	@NotEmpty
	private String newModel;
	@NotEmpty
	private String newPlatform;
	private String username;
	private String currentToken;
	private ReaderControlDTO currentItem;
	private List<ReaderControlDTO> listItems;

	public ControlDispositivosControlador() {
		init();
		currentToken = super.getTokenInContext();
		username = super.userLogged();
	}

	private void init() {
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			service.listISOMessage(Constantes.ISO003_BRAND_AND_MODEL_LIST,
					Constantes.READER_CONTROL_USERNAME, username,
					Constantes.READER_CONTROL_LIST_KEY);
			List<String> controlList = service.getList();

			if (controlList != null) {
				listItems = new ArrayList<ReaderControlDTO>();
				for (int i = 0; i < controlList.size(); i++) {
					String readerControl = controlList.get(i);
					List<String> control = Utils.convertList(readerControl);

					ReaderControlDTO dto = new ReaderControlDTO();
					dto.setIdReaderControl(new Long(control.get(0)));
					dto.setBrand(control.get(1));
					dto.setModel(control.get(2));
					dto.setPlatform(control.get(3));
					dto.setIsActive(Integer.valueOf(control.get(4)));
					listItems.add(dto);
				}
				super.setTokenInContext(service.getToken());
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage(Constantes.IOEXCEPTION_MESSAGE);
		} catch (ParseException e) {
			super.addWarningMessage(Constantes.PARSEEXCEPTION_MESSAGE);
		}
	}

	public String createControl() {
		List<Object> createData = new ArrayList<Object>();
		createData.add(newBrand);
		createData.add(newModel);
		createData.add(newPlatform);
		createData.add(username);
		createData.add(1);
		String string = Utils.buildStringData(createData);
		createUpdateReaderControlRequest(Constantes.ISO003_NEW_BRAND_AND_MODEL,
				string);
		return "";
	}

	public String updateControl() {
		List<Object> updateData = new ArrayList<Object>();
		updateData.add(brand);
		updateData.add(model);
		updateData.add(platform);
		updateData.add(username);
		updateData.add(isActive);
		String string = Utils.buildStringData(updateData);
		createUpdateReaderControlRequest(
				Constantes.ISO003_UPDATE_BRAND_AND_MODEL, string);
		return "";
	}

	public String deleteControl() {
		List<Object> deletePortalUserData = new ArrayList<Object>();
		deletePortalUserData.add(idReaderControl);
		deletePortalUserData.add(username);
		String deleteString = Utils.buildStringData(deletePortalUserData);
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			boolean response = service.isoMessageRequest(deleteString,
					Constantes.ISO003_DELETE_BRAND_AND_MODEL,
					Constantes.DELETE_CONF_METADATA);
			if (response) {
				if (service.getToken().equals(currentToken)) {
					super.invalidateSession();
				} else {
					super.setTokenInContext(service.getToken());
				}
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage("No fue posible conectarse con el servidor.");
		} catch (ParseException e) {
			super.addWarningMessage("Ocurrió un error al parsear la petición.");
		}
		return "";

	}

	public void createUpdateReaderControlRequest(String proccessingCode,
			String dataStructure) {
		String metadata = Constantes.CREATE_UPDATE_READER_CONTROL_METADATA;
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			boolean response = service.isoMessageRequest(proccessingCode,
					metadata, dataStructure);
			if (response) {
				if (service.getToken().equals(currentToken)) {
					super.invalidateSession();
				} else {
					super.setTokenInContext(service.getToken());
				}
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage(Constantes.IOEXCEPTION_MESSAGE);
		} catch (ParseException e) {
			super.addWarningMessage(Constantes.PARSEEXCEPTION_MESSAGE);
		}
	}

	private void selectedRow(ReaderControlDTO dto) {
		idReaderControl = String.valueOf(dto.getIdReaderControl());
		brand = dto.getBrand();
		model = dto.getModel();
		platform = dto.getPlatform();
		isActive = String.valueOf(dto.getIsActive());
	}

	public String getIdReaderControl() {
		return idReaderControl;
	}

	public void setIdReaderControl(String idReaderControl) {
		this.idReaderControl = idReaderControl;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getIsActive() {
		return isActive;
	}

	public void setIsActive(String isActive) {
		this.isActive = isActive;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String getPlatform() {
		return platform;
	}

	public void setPlatform(String platform) {
		this.platform = platform;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public ReaderControlDTO getCurrentItem() {
		return currentItem;
	}

	public void setCurrentItem(ReaderControlDTO currentItem) {
		selectedRow(currentItem);
		this.currentItem = currentItem;
	}

	public List<ReaderControlDTO> getListItems() {
		return listItems;
	}

	public void setListItems(List<ReaderControlDTO> listItems) {
		this.listItems = listItems;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getCurrentToken() {
		return currentToken;
	}

	public void setCurrentToken(String currentToken) {
		this.currentToken = currentToken;
	}

	public String getNewBrand() {
		return newBrand;
	}

	public String getNewIsActive() {
		return newIsActive;
	}

	public String getNewModel() {
		return newModel;
	}

	public String getNewPlatform() {
		return newPlatform;
	}

	public void setNewBrand(String newBrand) {
		this.newBrand = newBrand;
	}

	public void setNewIsActive(String newIsActive) {
		this.newIsActive = newIsActive;
	}

	public void setNewModel(String newModel) {
		this.newModel = newModel;
	}

	public void setNewPlatform(String newPlatform) {
		this.newPlatform = newPlatform;
	}

}
